/**
 * Created by Foold on 14-2-15.
 */

/*
 * GET users listing.
 */
var cname = require('path').basename(module.filename, '.js');
var routers = require('commons-dao')('article');
var ObjectID = require('mongodb').ObjectID;
var form = require('express-form');
var utils = require('my-utils');

var field = form.field;

function wmpcode(url) {

    var player = '<object classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6" height="500" id="test" width="600"><param name="url" value="' + url + '"/><embed allowchangedisplaysize="0" allowscan="0" animationatstart="0" autorewind="0" autostart="0" clicktoplay="0" enablecontextmenu="0" height="400" id="wmp" name="wmp" pluginspage="http://www.microsoft.com/Windows/Downloads/Contents/Products/MediaPlayer/" showaudiocontrols="1" showcaptioning="0" showcontrols="1" showdisplay="0" showgotobar="0" showpositioncontrols="0" showstatusbar="1" showtracker="0" src="' + url + '" transparentatstart="0" type="application/x-mplayer2" width="600" /></object>';

    return player;
}

function getRules(i18n) {

    return [];

}

function showChildDetail(req, res, pool, db, artcol) {
    var id = req.params.id;
    artcol.findOne({_id: routers.ObjectID(id)}, {fields: {_id: 1, name: 1, content: 1, createDate: 1, imagelist: 1, loopimage: 1}}, function (err, arcdoc) {
        if( notfound(res,pool,db,arcdoc)) return;
        
        var ptn2 = /\[(((http|ftp|https):\/\/)?[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?)\]/g;
       
		var content = arcdoc.content;
        arcdoc.content = content.replace(ptn2, wmpcode("$1"));
		pool.release(db); 
        res.render('frontal/child-content', {bean: arcdoc, layout: 'child-detail'});

    });
}


function showCtrlDetail(req, res, pool, db, artcol) {
    var arcId = req.params.tid;
    var aid = req.params.id;
    var rdata = {arcId:arcId};
    db.collection('mainmenu', function (err, mcol) {
        mcol.findOne({id: 'onlyone'}, {fields: {content: 1}}, function (err, menudoc) {

            var aquery = {"articlec.id": arcId};
            artcol.find(aquery, {fields: {_id: 1, name: 1, content: 1, createDate: 1}, sort: {createDate: -1}}, function (err, idresults) {
				if(notfound(res,pool,db,idresults))return;
				idresults.toArray(function (err, ndocs) {

				    if(!ndocs) {
						res.send(404, 'Sorry, we cannot find that!');
						pool.release(db); 
					}
                    rdata.menu = {
                        id: arcId,
                        content: menudoc.content

                    };
                    rdata.beans = ndocs;
                    rdata.layout = 'children';
                    rdata.beanIndex = 0;

                    for (var i = 0; i < ndocs.length; i++) {
                        if (ndocs[i]._id.toHexString() == aid) {
                            rdata.beanIndex = i;
                            rdata.bean = ndocs[i];
                            break;
                        }
                    }

                    res.render('frontal/ctrl-content', rdata);
                    pool.release(db);
                });

            });
        });
    });
}


function showChild(req, res, pool, db, artcol) {

    var rdata = {};
    var arcId = req.body["articlec.id"];
    db.collection('articlec', function (err, arcol) {
        arcol.findOne({_id: routers.ObjectID(arcId)}, {fields: {_id: 1, name: 1, url: 1, linkvalid: 1, playctrl: 1}}, function (err, arcdoc) {

            if(notfound(res,pool,db,arcdoc))return;
            if (arcdoc.url) {//begin has url specified

                res.redirect(arcdoc.url);

                pool.release(db);


                //end has url eepcified
            } else {

                db.collection('mainmenu', function (err, mcol) {
                    mcol.findOne({id: 'onlyone'}, {fields: {content: 1}}, function (err, menudoc) {


                        if (typeof(arcdoc.playctrl) != 'undefined' && arcdoc.playctrl == 'true') {

                            var aquery = {"articlec.id": arcId};
                            artcol.find(aquery, {fields: {_id: 1, name: 1, content: 1, createDate: 1}, sort: {createDate: -1}}, function (err, idresults) {
							    if(notfound(res,pool,db,idresults))return;
                                idresults.toArray(function (err, ndocs) {
                                    //console.log(rdata);

                                    rdata.arcId = arcId;
                                    rdata.menu = {
                                        id: arcId,
                                        content: menudoc.content

                                    };
                                    rdata.beans = ndocs;
                                    rdata.bean = ndocs[0];
                                    rdata.layout = 'children';
                                    rdata.beanIndex = 0;
                                    res.render('frontal/ctrl-content', rdata);
                                    pool.release(db);

                                });


                            });


                            return;
                        }


                        var limit = 10;
                        var p = req.query.p;
                        var skip = p;
                        if (!p || p < 1)p = 1;
                        var start = (skip - 1) * limit;
                        var aquery = {"articlec.id": arcId};
                        artcol.count(aquery, function (err, count) {
                            artcol.find(aquery,
                                {limit: limit, skip: start, fields: {_id: 1, name: 1, imagelist: 1, articlec: 1, createDate: 1, content: 1}, sort: {createDate: -1}}

                                , function (err, results) {
								if(notfound(res,pool,db,results))return;
                                    results.toArray(function (err, artdocs) {
                                        var baseurl = "/child/" + arcId;
                                        rdata.pagination = utils.pagination(count, p, baseurl, true);
                                        rdata.list = artdocs;
                                        rdata.layout = 'children';
                                        rdata.bean = arcdoc;
                                        if (artdocs) {

                                            var len = artdocs.length;
                                            switch (len) {
                                                case 0:
                                                    tempname = 'frontal/no-content';
                                                    break;
                                                case 1:
                                                    rdata.bean = artdocs[0];
                                                    tempname = 'frontal/content';
                                                    break;
                                                default:
                                                    tempname = 'frontal/newslist';

                                            }


                                        } else {
                                            tempname = 'frontal/content';
                                        }

                                        rdata.menu = {
                                            id: arcId,
                                            content: menudoc.content
                                        };


                                        //console.log(rdata);
                                        res.render(tempname, rdata);
                                        pool.release(db);
                                    });
                                });//end of find
                        });//end of count

                    });//end of collection article

                });
            }


        });
    });


}

function homeData(req, res, pool, db, artcol) {
    //home page

    var homedata = {};
    var rdata = {};

    db.collection("articlec", function (err, arccol) {

        arccol.findOne({area: "B"}, function (err, bartcdoc) {
			if(notfound(res,pool,db,bartcdoc))return;
            arccol.find({parentId: bartcdoc._id.toHexString()}
                , {skip: 0, limit: 6, fields: {_id: 1, name: 1}, sort: {sort: 1}}).toArray(function (err, bchildren) {


                    artcol.find({"area": {$in: ['A', 'C']}}, {fields: {_id: 1, name: 1, articlec: 1, area: 1, imagelist: 1}, sort: {createDate: -1}}, function (err, result) {
                        if(notfound(res,pool,db,result))return;
						result.toArray(function (err, artdocs) {

                            //----------------------------------------
                            ///console.log(artdocs);
                            if (err)console.log(err);


                            homedata['A'] = {
                                list: []
                            };

                            homedata['C'] = {
                                list: {}
                            };

                            for (var a in artdocs) {

                                (function (doc) {
                                    var areaa = doc['area'];
                                    if (areaa == 'A')
                                        homedata['A']['list'].push(doc);
                                    else {
                                        homedata['C']['list'][doc['articlec']['id']] = doc;
                                    }

                                })(artdocs[a]);


                            }


                            homedata['B'] = {
                                bean: bartcdoc,
                                list: bchildren
                            };
                            rdata.layout = false;
                            rdata.homedata = homedata;
                            res.render('frontal/index', rdata);
                            pool.release(db);

                            //----------------------------------------


                        });

                    });


                });


        });


    });


}

function notfound(res,pool,db,obj){
   if(!obj) {
						res.send(404, 'Sorry, we cannot find that!');
						pool.release(db); 
						return true;
					}
					return false;
}

function idValid(id){
    var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$");
    return checkForHexRegExp.test(id);
}

function checkid(id,res){
   var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$");
   return checkForHexRegExp.test(id);
   
}



module.exports = function (app, i18n) {
    routers.init(app, getRules(i18n));
    app.get('/child/:id', function (req, res) {
        var arcId = req.params.id;
		if(!checkid(arcId,res)){
res.send(404, 'Sorry, we cannot find that!');		
		   return;
		}
        req.body = {"articlec.id": arcId};
        routers.proxyHttpWithDb(req, res, showChild);
    });
    app.get('/child/:id/:p', function (req, res) {
        var arcId = req.params.id;
		if(!checkid(arcId,res)){		   
		res.send(404, 'Sorry, we cannot find that!');
		   return;
		}
        var p = req.params.p;
        res.redirect('/child/' + arcId + "?p=" + p);
    });

    app.get('/detail/:id', function (req, res) {
		var id = req.params.id;
		if(!checkid(id,res)){		   
		res.send(404, 'Sorry, we cannot find that!');
		   return;
		}
        routers.proxyHttpWithDb(req, res, showChildDetail);
    });

    app.get('/detailctrl/:tid/:id', function (req, res) {
		var tid = req.params.tid;
		if(!checkid(tid,res)){		   
		res.send(404, 'Sorry, we cannot find that!');
		   return;
		}
		var id = req.params.id;
		if(!checkid(id,res)){		   
		res.send(404, 'Sorry, we cannot find that!');
		   return;
		}
        routers.proxyHttpWithDb(req, res, showCtrlDetail);
    });

    app.get('/', function (req, res) {
        routers.proxyHttpWithDb(req, res, homeData);
    });
}